#include <stdio.h>
#include <stdlib.h>
#include <mpx_supt.h>

void list_dir(char*);
char** parse_cmd(char*);
//int cmp_cmd(char*, char*);
void date_cmd(char*);
void help(char*);
void display_version();
void terminateMPX();
void clear_screen();
void display_date();
int check_alias(char*);
//void new_alias(char*, char*);


void cmd_handler(char* input_buf){
	
	char** tokens = parse_cmd(input_buf);

	if(!strcmp(tokens[0], "date")){
		int arglen = strlen(tokens[1]);
		if( arglen > 0){
			date_cmd(tokens[1]);
		}
		else{
			display_date();
		}
	}
	else if(!strcmp(tokens[0], "alias")){
		if(check_alias(tokens[1])){
			//new_alias(tokens[0], tokens[1]);
			printf("new alias stuff.. to be continued\n");
		}
	}
	else if(!strcmp(tokens[0], "cls")){
		clear_screen();
	}
	else if(!strcmp(tokens[0], "ls")){
		//function from dir.cpp
		list_dir(tokens[1]);
	}
	else if(!strcmp(tokens[0], "help")){
		help(tokens[1]);
	}
	else if(!strcmp(tokens[0], "pcb")){
		handle_pcb(tokens[1]);
	}
	else if(!strcmp(tokens[0], "vrsn")){
		display_version();
	}
	else if(!strcmp(tokens[0], "exit")){
		terminateMPX();
	}
	else{
		printf("\"%s\" unrecognized command.\n", tokens[0]);
	}
	free(tokens[0]);
	free(tokens[1]);
	free(tokens);
}

//parses cmd and arguments from input buffer. returns array of "tokens"
char** parse_cmd(char* input){
	char** token_list = (char**)malloc(2 * sizeof(char*));
	token_list[0] = (char*)malloc(10 * sizeof(char));
	token_list[1] = (char*)malloc(80 * sizeof(char));

	int eos = strlen(input)-1;
	int i=0;
	while((input[i]==' ')||(input[i]=='\t')){
		i++;
	}
	while((input[eos]==' ')||(input[eos]=='\t')||(input[eos]=='\n')){
		eos--;
	}
	int j=0;
	while(!((input[i]==' ')||(input[i]=='\n')||(input[i]=='\t'))){
		token_list[0][j] = tolower(input[i]);
		j++;
		i++;
	}
	token_list[0][j]='\0';
	while((input[i]==' ')||(input[i]=='\t')){
		i++;
	}
	j=0;
	while(i<=eos){
		token_list[1][j] = tolower(input[i]);
		j++;
		i++;
	}
	token_list[1][j]='\0';
	return token_list;
}
